<template>
  <div style="padding: 2rem;">
    <div style="display: flex; justify-content: center; align-items: center;">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="歌曲" style="margin-bottom: 0;">
          <el-input style="width: 145px;" v-model="searchForm.songName" placeholder="请输入歌曲名称"></el-input>
        </el-form-item>
        <el-form-item label="艺人" style="margin-bottom: 0;">
          <el-input style="width: 145px;" v-model="searchForm.artistName" placeholder="请输入艺人名称"></el-input>
        </el-form-item>
        <el-form-item label="歌单" style="margin-bottom: 0;">
          <el-select style="width: 145px;" v-model="searchForm.playlistId" placeholder="请选择歌单" clearable filterable>
            <el-option v-for="item in playlists" :key="item.playlistId" :label="item.playlistName"
              :value="item.playlistId" />
          </el-select>
        </el-form-item>
        <el-form-item label="发行年份" style="margin-bottom: 0;">
          <el-input v-model.number="searchForm.releasedYear" placeholder="请输入发行年份" type="number"
            style="width: 145px"></el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 0; margin-right: 12px;">
          <el-button type="primary" @click="handleSearch" plain>查询</el-button>
        </el-form-item>
      </el-form>
      <el-button type="success" @click="openDialog('add')" plain>新建</el-button>
      <el-button type="danger" @click="handleBatchDelete" plain>批量删除</el-button>
    </div>
    <el-table :data="tableData" style="width: 100%; margin-top: 15px;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="songId" label="ID" width="" />
      <el-table-column prop="songName" label="歌曲" width="" />
      <el-table-column prop="albumName" label="专辑" width="" />
      <el-table-column prop="artistName" label="艺人" width="" />
      <el-table-column prop="playlistName" label="歌单名称" width="" />
      <el-table-column prop="releasedYear" label="发行年份" width="" />
      <el-table-column prop="insertedAt" label="插入时间" width="" :formatter="formatDate" />
      <el-table-column prop="updatedAt" label="更新时间" width="" :formatter="formatDate" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openDialog('edit', scope.row)">编辑</el-button>
          <el-button link type="danger" size="small" @click="handleDelete(scope.row.songId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container" style="margin-top: 20px; width: 100%;">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 40]"
        :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <el-dialog :title="dialogTitle" v-model="dialogVisible" align-center>
      <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px">
        <el-form-item label="歌曲名称" prop="songName" style="margin-bottom: 20px;">
          <el-input v-model="addForm.songName"></el-input>
        </el-form-item>
        <el-form-item label="艺人名称" prop="artistName" style="margin-bottom: 20px;">
          <el-input v-model="addForm.artistName"></el-input>
        </el-form-item>
        <el-form-item label="专辑名称" prop="albumName" style="margin-bottom: 20px;">
          <el-input v-model="addForm.albumName"></el-input>
        </el-form-item>
        <el-form-item label="归属歌单" prop="playlistId" style="margin-bottom: 20px;">
          <el-select v-model="addForm.playlistId" placeholder="请选择歌单">
            <el-option v-for="item in playlists" :key="item.playlistId" :label="item.playlistName"
              :value="item.playlistId" />
          </el-select>
        </el-form-item>
        <el-form-item label="发行年份" prop="releasedYear" style="margin-bottom: 20px;">
          <el-input v-model.number="addForm.releasedYear" type="number"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { searchStudentByPage, addStudent, updateStudent, deleteStudent } from "@/api/song";
import { getClassesList } from "@/api/playlists";
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { ComponentSize } from 'element-plus'
import dayjs from 'dayjs'

const currentPage = ref(1)
const pageSize = ref(10)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const tableData = ref([])
const total = ref(0)
const searchForm = ref({
  songName: '',
  artistName: '',
  playlistId: '',
  albumName: '',
  releasedYear: null
})
const playlists = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加歌曲')
const addForm = ref({
  sid: null,
  songName: '',
  artistName: '',
  playlistId: '',
  releasedYear: null
})
const rules = {
  songName: [{ required: true, message: '请输入歌曲名称', trigger: 'blur' }],
  artistName: [{ required: true, message: '请输入艺人名称', trigger: 'blur' }],
  playlistId: [{ required: true, message: '请选择歌单', trigger: 'change' }],
  albumName: [{ required: true, message: '请选择专辑名称', trigger: 'change' }],
  releasedYear: [
    { required: true, message: '请输入发行年份', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!Number.isInteger(value)) {
          callback(new Error('发行年份必须为整数'))
        } else if (value < 1900 || value > new Date().getFullYear()) {
          callback(new Error('发行年份必须在1900到当前年份之间'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ]
}
const addFormRef = ref(null)
const selectedSongs = ref([])

const openDialog = (type: string, row: any = null) => {
  if (type === 'add') {
    dialogTitle.value = '添加歌曲'
    addForm.value = {
      sid: null,
      songName: '',
      artistName: '',
      playlistId: '',
      releasedYear: null
    }
  } else if (type === 'edit' && row) {
    dialogTitle.value = '编辑歌曲'
    addForm.value = { ...row }
  }
  dialogVisible.value = true
}

const handleSave = async () => {
  addFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (addForm.value.songId) {
          await updateStudent(addForm.value)
          ElMessage.success('歌曲信息更新成功')
        } else {
          await addStudent(addForm.value)
          ElMessage.success('歌曲新增成功')
        }
        dialogVisible.value = false
        handleSearch()
      } catch (error) {
        ElMessage.error('操作失败，请重试')
      }
    }
  })
}

const handleDelete = async (songId: string) => {
  try {
    await deleteStudent(songId)
    ElMessage.success('歌曲删除成功')
    handleSearch()
  } catch (error) {
    ElMessage.error('删除失败，请重试')
  }
}

const handleBatchDelete = async () => {
  if (selectedSongs.value.length === 0) {
    ElMessage.warning('请选择要删除的歌曲')
    return
  }
  const songIds = selectedSongs.value.map(song => song.songId).join(',')
  try {
    await deleteStudent(songIds)
    ElMessage.success('歌曲批量删除成功')
    handleSearch()
  } catch (error) {
    ElMessage.error('批量删除失败，请重试')
  }
}

const handleSelectionChange = (selection: any[]) => {
  selectedSongs.value = selection
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  handleSearch()
}

const handleSearch = async () => {
  const response = await searchStudentByPage(currentPage.value, pageSize.value, searchForm.value)
  total.value = response.data.pageResult.total
  tableData.value = response.data.pageResult.rows
}

const formatDate = (row: any, column: any, cellValue: string) => {
  return dayjs(cellValue).format('YYYY-MM-DD')
}

onMounted(async () => {
  const response = await getClassesList()
  playlists.value = response.data.list
  handleSearch()
})
</script>

<style>
.pagination-container {
  display: flex;
  justify-content: center;
}
</style>
